/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package MainPackage;

import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author n.kaminski
 */
@XmlRootElement( name="Userlist" )
public class Userlist {             
    
    private List<User> users = new ArrayList<User>();
    
    public Userlist() throws JAXBException, NoSuchAlgorithmException{
        //nichts!!!
    }
    
    /**
     * Laedt die User aus der User.xml Datei.
     */
    public static Userlist loadUserlist(){
        File file = new File(Options.USERXMLPATH);
        Userlist ul = null;
        try{
            ul= new Userlist();
        }catch(Exception ex){
            //
        }
        if(file.exists()){
            ul = JAXB.unmarshal(file, Userlist.class);
        }
        
        if(Options.DEBUG){
            System.out.println(ul.users.toString());
        }
        ul.CalcAllReferenzwerte();
        return ul;
    }
    
    /**
     * Exportiert die User und die Daten aus Userlist in die standart Datei
     */
    public void export(){
        File file = new File(Options.USERXMLPATH);
        JAXB.marshal(this, file);        
    }
    
    public boolean enthaeltUser(String name){
        for(int i = 0; i < users.size(); ++i){
            if(users.get(i).getName().equals(name))
                return true;
        }
        
        return false;
    }
    
    public User getUser(String name){
        for(int i = 0; i < users.size(); ++i){
            if(users.get(i).getName().equals(name))
                return users.get(i);
        }
        
        return null;
    }
    
    public void addUser(User user){
        if(!enthaeltUser(user.getName())){
            this.users.add(user);
        }
    }
    
    private void CalcAllReferenzwerte(){
        for(int i = 0; i < users.size(); ++i){
            users.get(i).ReferenzwerteNeuBerechnen();
        }
    }
    
    //Getter & Setter fuer Xml
    @XmlElement( name = "User" )
    public List<User> getUsers(){
        return users;
    }
    public void setUsers(List<User> users){
        this.users = users;
    }
    
    @XmlElement( name = "MaxUserID")
    public int getMaxUserID(){
        return User.getMaxUserID();
    }
    public void setMaxUserID(int maxUserID){
        User.setMaxUserID(maxUserID);
    }
    
}
